﻿import cgi
import base64

from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.api import users

#from entities import DonDangTuyenEntities
from entities import *
from Entities import *
#from entities import TuyenDungNguoiDungEntities
#from entities import DonDangTuyenEntities
from entities import TrangThaiEntities


from google.appengine.api import images
#--------------------------------------------
# -- NhaTuyenDung
#--------------------------------------------
def Get(keyNguoiDung, TenThuongHieu = "", Email = "", TrangThaiID=0, QuiMoID=0, LinhVucID=0, NhaTuyenDungID=0):
    try:
        nguoidung = NguoiDung.get(db.Key(keyNguoiDung)) 
    except:
        return "Invalid Key"
    nhatuyendung_list = []
    results = NhaTuyenDung.all()
    if Email != "":
        results = results.filter("Email =", Email)    
    if TenThuongHieu != "":
        results = results.filter("TenThuongHieu >=",TenThuongHieu).filter("TenThuongHieu <=", unicode(TenThuongHieu) + u'\ufffd')           
    tuyendungs = TuyenDungNguoiDungEntities.Get(keyNguoiDung,0)    
    results = results.filter("__key__ IN", tuyendungs)
    
    if int(QuiMoID) > 0:
        try:
            quimo = QuiMo.get_by_id(int(QuiMoID))
            results = results.filter("QuiMoID", quimo)
        except:
            return "Invalid QuiMoID"
            
    if int(LinhVucID) > 0:
        try:
            linhvuc = LinhVuc.get_by_id(int(LinhVucID))
            results = results.filter("LinhVucID", linhvuc)
        except:
            return "Invalid LinhVucID"            
    
    if int(TrangThaiID) > 0:
        try:
            trangthai = TrangThaiXetDuyet.get_by_id(int(TrangThaiID))
            results = results.filter("TrangThaiID", trangthai)
        except:
            return "Invalid TrangThaiID"       
    
    if NhaTuyenDungID > 0:
        try:
            nhatuyendung = NhaTuyenDung.get_by_id(NhaTuyenDungID)
        except:
            return "Invalid NhaTuyenDungID"
        nhatuyendung_dict ={}
        dondangtuyens = DonDangTuyenEntities.Get(keyNguoiDung, NhaTuyenDungID)
        nhatuyendung_dict['NhaTuyenDungID'] = nhatuyendung.key().id()
        nhatuyendung_dict['TenThuongHieu'] = nhatuyendung.TenThuongHieu
        nhatuyendung_dict['MieuTa'] = str(nhatuyendung.MieuTa.encode('utf-8'))
        nhatuyendung_dict['Email'] = nhatuyendung.Email
        nhatuyendung_dict['SoDienThoai'] = nhatuyendung.SoDienThoai
        nhatuyendung_dict['TenLinhVuc'] = nhatuyendung.LinhVucID.TenLinhVuc
        nhatuyendung_dict['NguoiLienHe'] = nhatuyendung.NguoiLienHe
        nhatuyendung_dict['QuiMo'] = nhatuyendung.QuiMoID.SoLuong
        #if nhatuyendung.AnhDaiDien != "":
        nhatuyendung_dict['AnhDaiDienLink'] = '/img?img_id=' + str(nhatuyendung.key())
        nhatuyendung_dict['Website'] = nhatuyendung.Website
        nhatuyendung_dict['Lat'] = nhatuyendung.ViTri.lat
        nhatuyendung_dict['Lng'] = nhatuyendung.ViTri.lon
        nhatuyendung_dict['ViTriText'] = nhatuyendung.ViTriText
        #nhatuyendung_dict['TrangThaiID'] = nhatuyendung.TrangThaiID
        nhatuyendung_dict['TenTrangThai'] = nhatuyendung.TrangThaiID.TenTrangThai
        nhatuyendung_dict['NguoiDungID'] = nhatuyendung.NguoiDungID
        nhatuyendung_dict['SoDonDangTuyen'] = len(dondangtuyens)
        nhatuyendung_list.append(nhatuyendung_dict)
    else:
        #nhatuyendungs = results.filter("NguoiDung =", nguoidung)
        for nhatuyendung in results:
            dondangtuyens = DonDangTuyenEntities.Get(keyNguoiDung, nhatuyendung.key().id())
            nhatuyendung_dict ={}
            nhatuyendung_dict['NhaTuyenDungID'] = nhatuyendung.key().id()
            nhatuyendung_dict['TenThuongHieu'] = nhatuyendung.TenThuongHieu
            nhatuyendung_dict['MieuTa'] = str(nhatuyendung.MieuTa.encode('utf-8'))
            nhatuyendung_dict['Email'] = nhatuyendung.Email
            nhatuyendung_dict['SoDienThoai'] = nhatuyendung.SoDienThoai
            nhatuyendung_dict['TenLinhVuc'] = nhatuyendung.LinhVucID.TenLinhVuc
            nhatuyendung_dict['NguoiLienHe'] = nhatuyendung.NguoiLienHe
            nhatuyendung_dict['QuiMo'] = nhatuyendung.QuiMoID.SoLuong
            #if nhatuyendung.AnhDaiDien != "":
            nhatuyendung_dict['AnhDaiDienLink'] = '/img?img_id=' + str(nhatuyendung.key()) 
            nhatuyendung_dict['Website'] = nhatuyendung.Website
            nhatuyendung_dict['Lat'] = nhatuyendung.ViTri.lat
            nhatuyendung_dict['Lng'] = nhatuyendung.ViTri.lon
            nhatuyendung_dict['ViTriText'] = nhatuyendung.ViTriText
            #nhatuyendung_dict['TrangThaiID'] = nhatuyendung.TrangThaiID
            nhatuyendung_dict['TenTrangThai'] = nhatuyendung.TrangThaiID.TenTrangThai
            nhatuyendung_dict['NguoiDungID'] = nhatuyendung.NguoiDungID
            nhatuyendung_dict['SoDonDangTuyen'] = len(dondangtuyens)
            nhatuyendung_list.append(nhatuyendung_dict)
    tuple_nhatuyendung = tuple(nhatuyendung_list)  
    return tuple_nhatuyendung

def GetID(keyNguoiDung):
    nhatuyendung_list = []
    results = NhaTuyenDung.all()
    tuyendungs = TuyenDungNguoiDungEntities.Get(keyNguoiDung,0)    
    results = results.filter("__key__ IN", tuyendungs)
    for nhatuyendung in results:
        nhatuyendung_list.append(nhatuyendung.key()) 
    return nhatuyendung_list

def All():
    nhatuyendung_list = []
    nhatuyendungs = NhaTuyenDung.all()
    for nhatuyendung in nhatuyendungs:
        nhatuyendung_dict ={}
        nhatuyendung_dict['NhaTuyenDungID'] = nhatuyendung.key().id()
        nhatuyendung_dict['TenThuongHieu'] = nhatuyendung.TenThuongHieu
        nhatuyendung_dict['MieuTa'] = str(nhatuyendung.MieuTa.encode('utf-8'))
        nhatuyendung_dict['Email'] = nhatuyendung.Email
        nhatuyendung_dict['SoDienThoai'] = nhatuyendung.SoDienThoai
        nhatuyendung_dict['TenLinhVuc'] = nhatuyendung.LinhVucID.TenLinhVuc
        nhatuyendung_dict['TenTrangThai'] = nhatuyendung.TrangThaiID.TenTrangThai
        nhatuyendung_dict['TrangThaiID'] = nhatuyendung.TrangThaiID.key().id()
        nhatuyendung_list.append(nhatuyendung_dict)
    tuple_nhatuyendung = tuple(nhatuyendung_list)  
    return tuple_nhatuyendung
        
    
    
def Add(keyNguoiDung, TenThuongHieu, MieuTa, Email, SoDienThoai, LinhVucID, NguoiLienHe, QuiMoID, AnhDaiDien,  Website, ViTriText, ViTri, TrangThaiID, NguoiDungID):
    try:
        nguoidung = NguoiDung.get(db.Key(keyNguoiDung)) 
    except:
        return "Mã xác nhận ko hợp lệ"
    nhatuyendung = db.GqlQuery("SELECT * FROM NhaTuyenDung WHERE Email = :1",
                              Email)
    if nhatuyendung.count() > 0:
	    return "Email đã tồn tại"
    nhatuyendung = db.GqlQuery("SELECT * FROM NhaTuyenDung WHERE TenThuongHieu = :1",
                                TenThuongHieu)

    if nhatuyendung.count() > 0:
		return "Tên Thương Hiệu đã tồn tại"
    linhvuc = LinhVuc.get_by_id(int(LinhVucID))
    quimo = QuiMo.get_by_id(int(QuiMoID))
    trangthai = TrangThaiXetDuyet.get_by_id(int(TrangThaiID))
     
    #try:
    nhatuyendung = NhaTuyenDung(TenThuongHieu = TenThuongHieu, MieuTa = MieuTa, Email = Email, SoDienThoai = SoDienThoai, NguoiLienHe = NguoiLienHe, LinhVucID = linhvuc, QuiMoID = quimo,ViTri = ViTri,TrangThaiID=trangthai)
    #avatar = images.resize(AnhDaiDien, 32, 32)
    if AnhDaiDien != "":
        avatar = images.resize(AnhDaiDien, 100, 100)
        nhatuyendung.AnhDaiDien = db.Blob(avatar)
    nhatuyendung.NguoiDungID = NguoiDungID
    nhatuyendung.Website = Website
    nhatuyendung.ViTriText = ViTriText
    nhatuyendung.put()
        #except Exception: 
            #return "Error"
    TuyenDungNguoiDungEntities.Add(keyNguoiDung, nhatuyendung.key().id())
    return "Complete"

def AddService(keyNguoiDung, TenThuongHieu, MieuTa, Email, SoDienThoai, LinhVucID, NguoiLienHe, QuiMoID, AnhDaiDien,  Website, ViTriText, ViTri, TrangThaiID, NguoiDungID):
    try:
        nguoidung = NguoiDung.get(db.Key(keyNguoiDung)) 
    except:
        return "Mã xác nhận ko hợp lệ"
    nhatuyendung = db.GqlQuery("SELECT * FROM NhaTuyenDung WHERE Email = :1",
                              Email)
    if nhatuyendung.count() > 0:
	    return "Email đã tồn tại"
    nhatuyendung = db.GqlQuery("SELECT * FROM NhaTuyenDung WHERE TenThuongHieu = :1",
                                TenThuongHieu)

    if nhatuyendung.count() > 0:
		return "Tên Thương Hiệu đã tồn tại"
    linhvuc = LinhVuc.get_by_id(int(LinhVucID))
    quimo = QuiMo.get_by_id(int(QuiMoID))
    trangthai = TrangThaiXetDuyet.get_by_id(int(TrangThaiID))
     
    #try:
    nhatuyendung = NhaTuyenDung(TenThuongHieu = TenThuongHieu, MieuTa = MieuTa, Email = Email, SoDienThoai = SoDienThoai, NguoiLienHe = NguoiLienHe, LinhVucID = linhvuc, QuiMoID = quimo,ViTri = ViTri,TrangThaiID=trangthai)
    #avatar = images.resize(AnhDaiDien, 32, 32)
    if AnhDaiDien != "":
        image = base64.decodestring(AnhDaiDien)
        avatar = images.resize(image, 100, 100)
        nhatuyendung.AnhDaiDien = db.Blob(avatar)
    nhatuyendung.NguoiDungID = NguoiDungID
    nhatuyendung.Website = Website
    nhatuyendung.ViTriText = ViTriText
    nhatuyendung.put()
        #except Exception: 
            #return "Error"
    TuyenDungNguoiDungEntities.Add(keyNguoiDung, nhatuyendung.key().id())
    return "Complete"    
    
def Update(keyNguoiDung,NhaTuyenDungID,TenThuongHieu, MieuTa, SoDienThoai, LinhVucID, NguoiLienHe, QuiMoID, AnhDaiDien,  Website, ViTriText, Lat, Lng):
    try:
        nguoidung = NguoiDung.get(db.Key(keyNguoiDung)) 
    except:
        return "Invalid Key"
    nhatuyendung_update = NhaTuyenDung.get_by_id(NhaTuyenDungID)
    nhatuyendung = db.GqlQuery("SELECT * FROM NhaTuyenDung WHERE TenThuongHieu = :1  AND SoDienThoai =:2 AND NguoiDung = :3",
                              TenThuongHieu, SoDienThoai, nguoidung)
    linhvuc = LinhVuc.get_by_id(LinhVucID)
    quimo = QuiMo.get_by_id(QuiMoID)
    if nhatuyendung_update != None:    
        if nhatuyendung.count() == 0:
            nhatuyendung_update.TenThuongHieu = TenThuongHieu
            nhatuyendung_update.MieuTa = MieuTa
            #nhatuyendung_update.Email = Email
            nhatuyendung_update.SoDienThoai = SoDienThoai

           # nhatuyendung_update.TrangThaiID = TrangThaiID
            if AnhDaiDien != "":
                nhatuyendung_update.AnhDaiDien = db.Blob(AnhDaiDien)
            nhatuyendung_update.LinhVucID = linhvuc
            nhatuyendung_update.NguoiLienHe = NguoiLienHe
            nhatuyendung_update.Website = Website
            nhatuyendung_update.ViTriText = ViTriText
            nhatuyendung_update.ViTri = db.GeoPt(lat=float(Lat), lon=float(Lng))
            nhatuyendung_update.QuiMoID = quimo
            nhatuyendung_update.put()
            return "Complete"
        else:
            return "Duplicate"
    else:
        return "Error"

def UpdateService(keyNguoiDung,NhaTuyenDungID,TenThuongHieu, MieuTa, SoDienThoai, LinhVucID, NguoiLienHe, QuiMoID, AnhDaiDien,  Website, ViTriText, Lat, Lng):
    try:
        nguoidung = NguoiDung.get(db.Key(keyNguoiDung)) 
    except:
        return "Invalid Key"
    nhatuyendung_update = NhaTuyenDung.get_by_id(NhaTuyenDungID)
    nhatuyendung = db.GqlQuery("SELECT * FROM NhaTuyenDung WHERE TenThuongHieu = :1  AND SoDienThoai =:2 AND NguoiDung = :3",
                              TenThuongHieu, SoDienThoai, nguoidung)
    linhvuc = LinhVuc.get_by_id(LinhVucID)
    quimo = QuiMo.get_by_id(QuiMoID)
    if nhatuyendung_update != None:    
        if nhatuyendung.count() == 0:
            nhatuyendung_update.TenThuongHieu = TenThuongHieu
            nhatuyendung_update.MieuTa = MieuTa
            nhatuyendung_update.SoDienThoai = SoDienThoai
            if AnhDaiDien != "":
                image = base64.decodestring(AnhDaiDien)
                #avatar = images.resize(image, 100, 100)
                #nhatuyendung_update.AnhDaiDien = db.Blob(avatar)
                nhatuyendung_update.AnhDaiDien = db.Blob(image)
            nhatuyendung_update.LinhVucID = linhvuc
            nhatuyendung_update.NguoiLienHe = NguoiLienHe
            nhatuyendung_update.Website = Website
            nhatuyendung_update.ViTriText = ViTriText
            nhatuyendung_update.ViTri = db.GeoPt(lat=float(Lat), lon=float(Lng))
            nhatuyendung_update.QuiMoID = quimo
            nhatuyendung_update.put()
            return "Complete"
        else:
            return "Duplicate"
    else:
        return "Error"        
        
def GetCurrent(Email):
    nhatuyendungs = db.GqlQuery("SELECT * FROM NhaTuyenDung WHERE Email = :1",
                              Email)
    id = None
    if nhatuyendungs.count() >0:
        for nhatuyendung in nhatuyendungs:
           id = nhatuyendung.key().id()  
    return id


def GetViTriRadian(lat, lng, radian):
    #query = "SELECT ( " + 3959 * acos( cos( radians(lat_t) )+"* cos( radians( ViTri.lat ) ) * cos( radians( ViTri.lon ) - " + (radians(lat_t) )+ sin( radians(lng_t) ) +"* sin( radians( ViTri.lat ) ) ) ) AS distance FROM NhaTuyenDung HAVING distance <"
    south = lat - radian
    north = lat + radian
    west = lng - radian
    east  = lng + radian
    #results = db.GqlQuery("SELECT ( 3959 * acos( cos( radians(:1) ) * cos( radians( ViTri.lat ) ) * cos( radians( ViTri.lon ) - radians(:2) )+ sin( radians(:3) ) * sin( radians( ViTri.lat ) ) ) ) AS distance FROM NhaTuyenDung HAVING distance < :4", 
    #                        lat_t, lng_t,lat_t, rad)
    results = GetLocation(east,west,south,north)
    return results

    
def GetLocation(east, west, south, north):
    #tuyendungs = TuyenDungNguoiDungEntities.Get(Entities.GetKey())  
    #results = NhaTuyenDung.all().filter("__key__ IN", tuyendungs)
    results = NhaTuyenDung.all()
    results = results.filter("ViTri >=", db.GeoPt(lat=south, lon = west)).filter("ViTri <=",db.GeoPt(lat=north, lon=east))
    TrangThaiID =  TrangThaiEntities.GetID(Entities.GetKey(), u'Hợp lệ')
    trangthai = TrangThaiXetDuyet.get_by_id(TrangThaiID)
    results = results.filter("TrangThaiID", trangthai)
    #results = db.GqlQuery("SELECT * FROM NhaTuyenDung WHERE ViTri >=:1 and ViTri <= :2", db.GeoPt(lat=south, lon=west), db.GeoPt(lat=north, lon=east))
    nhatuyendung_list = []
    for nhatuyendung in results:
        nhatuyendung_dict ={}
        nhatuyendung_dict['NhaTuyenDungID'] = nhatuyendung.key().id()
        nhatuyendung_dict['TenThuongHieu'] = nhatuyendung.TenThuongHieu
        nhatuyendung_dict['MieuTa'] = str(nhatuyendung.MieuTa.encode('utf-8'))
        nhatuyendung_dict['Email'] = nhatuyendung.Email
        nhatuyendung_dict['SoDienThoai'] = nhatuyendung.SoDienThoai
        nhatuyendung_dict['LinhVuc'] = nhatuyendung.LinhVucID.TenLinhVuc
        nhatuyendung_dict['TrangThai'] = nhatuyendung.TrangThaiID.TenTrangThai
        nhatuyendung_dict['ViTriText'] = nhatuyendung.ViTriText
        nhatuyendung_dict['NguoiLienHe'] = nhatuyendung.NguoiLienHe
        nhatuyendung_dict['QuiMo'] = nhatuyendung.QuiMoID.SoLuong
        nhatuyendung_dict['Website'] = nhatuyendung.Website
        nhatuyendung_dict['AnhDaiDienLink'] = '/img?img_id=' + str(nhatuyendung.key()) 
        nhatuyendung_dict['Lat'] = nhatuyendung.ViTri.lat
        nhatuyendung_dict['Lng'] = nhatuyendung.ViTri.lon
        nhatuyendung_list.append(nhatuyendung_dict)
    tuple_nhatuyendung = tuple(nhatuyendung_list)          
    return tuple_nhatuyendung
    
def Delete(keyNguoiDung, NhaTuyenDungID):
    try:
        nguoidung = NguoiDung.get(db.Key(keyNguoiDung)) 
    except:
        return "Invalid Key"
    return TuyenDungNguoiDungEntities.Delete(keyNguoiDung, NhaTuyenDungID)

def UpdateStatus(NhaTuyenDungID,TrangThaiID):
    trangthai = TrangThaiXetDuyet.get_by_id(TrangThaiID)
    nhatuyendung = NhaTuyenDung.get_by_id(NhaTuyenDungID)
    nhatuyendung.TrangThaiID = trangthai
    nhatuyendung.put()
    return "Complete"
    
    #return TrangThaiID